﻿using Abp.Dependency;
using Abp.Events.Bus.Handlers;
using shenghua.Order.Orders.EventDatas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Commodity.Commodities
{
    class CommodityEventHandler: 
        IEventHandler<AfterGenerateOrderEventData>, 
        IEventHandler<AfterCancelOrderEventData>, 
        IEventHandler<AfterFinishOrderEventData>,
        IEventHandler<AfterPaymentOrderEventData>,
        ITransientDependency
    {
        private readonly CommodityManager _commodityManager;

        public CommodityEventHandler(
            CommodityManager commodityManager
            )
        {
            _commodityManager = commodityManager;
        }

        public void HandleEvent(AfterGenerateOrderEventData eventData)
        {
            // 下单减库存
            foreach(var item in eventData.Details)
            {
                if(item.InventoryDeductionType == Basics.InventoryDeductionType.Ordered)
                {
                    _commodityManager.ChangeInventory(item.CommodityId, item.ShoppingOptionId, -item.Count).Wait();
                }
            }
        }

        public void HandleEvent(AfterCancelOrderEventData eventData)
        {
            // 下单减库存，取消订单库存加回去
            foreach (var item in eventData.Details)
            {
                if(item.InventoryDeductionType == Basics.InventoryDeductionType.Ordered)
                {
                    _commodityManager.ChangeInventory(item.CommodityId, item.ShoppingOptionId, item.Count).Wait();
                }
            }
        }

        public void HandleEvent(AfterPaymentOrderEventData eventData)
        {
            // 付款减库存
            foreach (var item in eventData.Details)
            {
                if (item.InventoryDeductionType == Basics.InventoryDeductionType.Paid)
                {
                    _commodityManager.ChangeInventory(item.CommodityId, item.ShoppingOptionId, -item.Count).Wait();
                }
            }
        }

        public void HandleEvent(AfterFinishOrderEventData eventData)
        {
            // 完成订单增加销量
            foreach (var item in eventData.Details)
            {
                _commodityManager.ChangeSalesVolume(item.CommodityId, item.ShoppingOptionId, item.Count).Wait();
            }
        }
    }
}
